package com.yuanluludev.gaode.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.yuanluludev.gaode.utils.LocUtils
import com.yuanluludev.lib_utils.util.LogUtils
import com.yuanluludev.lib_utils.util.TimeUtils

/**
 * yuanLuLu
 * 前后台持续定位服务
 */
class LocationService : Service() {


    /**
     * 对外暴露 获取到的最新aMapLocation
     */
    companion object {
        //有值的
        var currentAddress = ""
        var currentLat = 0.0
        var currentLng = 0.0

        var latestLocation: AMapLocation? = null
    }

    //声明AMapLocationClient类对象
    private var mLocationClient: AMapLocationClient? = null

    //声明AMapLocationClientOption对象
    private var mLocationOption: AMapLocationClientOption? = null

    //声明定位回调监听器
    private var mLocationListener = AMapLocationListener { aMapLocation ->
        if (aMapLocation != null) {
            latestLocation = aMapLocation
            if (aMapLocation.errorCode == 0) {
                aMapLocation.apply {
                    currentAddress = this.address
                    currentLat = this.altitude
                    currentLng = this.longitude
                }
            }
            LogUtils.e(aMapLocation.toString().replace("#","\n"))
            LogUtils.e(TimeUtils.millis2String(aMapLocation.time))
        }
    }

    override fun onBind(intent: Intent?): IBinder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        initLocation()
        return super.onStartCommand(intent, flags, startId)
    }

    private fun initLocation() {
        //避免service重启多次初始化
        if (mLocationClient == null) {
            mLocationClient = AMapLocationClient(this)
            mLocationClient?.setLocationListener(mLocationListener)
            //初始化AMapLocationClientOption对象
            mLocationOption = AMapLocationClientOption().apply {
                //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
                locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms
                interval = LocUtils.locPeriod
                //设置是否返回地址信息（默认返回地址信息）
                isNeedAddress = true
            }
            //给定位客户端对象设置定位参数
            mLocationClient?.setLocationOption(mLocationOption)
            //启动定位
            mLocationClient?.startLocation()
        } else {
            if (mLocationClient?.isStarted == false) {
                mLocationClient?.startLocation()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.stopLocation()
        mLocationClient?.onDestroy()
    }

}
